<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-08-13 11:07:46
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-08-13 17:53:34
 * @FilePath: \flex-\6-1 canvas 直线相交求点.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    const line1 = [
      // line1 上点 1
      {
        x: 100,
        y: 0,
      },
      // line1 上点 2
      {
        x: 0,
        y: -100,
      },
    ];
    const line2 = [
      {
        x: 0,
        y: 0,
      },
      {
        x: 100,
        y: 10,
      },
    ];
    // 求解直线的解析方程
    /*
      Ax + By + C = 0
      return {
        A, B, C
      }
    */
    function resolveLineParamsFunction(line) {
      // 如果是竖直线
      if (line[1].x - line[0].x === 0) {
        return {
          a: 1,
          b: 0,
          c: -line[0].x,
        };
      }
      // 如果是水平线
      if (line[1].y - line[0].y === 0) {
        return {
          a: 0,
          b: 1,
          c: -line[0].y,
        };
      }
      // 斜率，tan
      const k = (line[1].y - line[0].y) / (line[1].x - line[0].x);
      const b = line[0].y - k * line[0].x;
      return {
        a: k,
        b: -1,
        c: b,
      };
    }

    // 求交点
    function resolveCrossPoint(line1, line2) {
      let line1Param = resolveLineParamsFunction(line1);
      let line2Param = resolveLineParamsFunction(line2);
      let d = line1Param.a * line2Param.b - line2Param.a * line1Param.b;
      if(d === 0) {
        if(line1Param.c === line2Param.c) {
          console.log("直线重合！");
          return false;
        }
        if(line1Param.c != line2Param.c) {
          console.log("直线平行！");
          return false;
        }
      }
      
      let x = (-line1Param.c * line2Param.b - (-line2Param.c * line1Param.b)) / d;
      let y = (-line2Param.c * line1Param.a - (-line1Param.c * line2Param.a)) / d;
      console.log(line1Param.c,line2Param.b,line2Param.c,line2Param.b);
      return {
        x,
        y,
      };
    }
    console.log(resolveCrossPoint(line1, line2));
  </script>
</html>
